<template>
  <div
      style="height: 100%;width: 100%;background-color: #001529; transition: background-color 0.1s linear 0s;">
    <div v-if="data.validateFailed"
         style="display: flex;justify-content: center;align-items: center;height: 100%;width: 100%">
      <div class="flex flex-wrap gap-4">
        <el-card style="font-size: 30px; color: #666" shadow="always">文件已被取消分享（或分享文件不存在）</el-card>
      </div>
    </div>


    <div v-else style="height: 100%;width: 100%;display: flex;align-items: center;justify-content: center">
      <!--    背景图片  -->
      <span class="iconfont-myicons"
            style="color: #09abff;font-size: 300px;overflow: hidden;position: fixed;;z-index: -10">&#xe615;</span>
      <div
          style="width: 90%;height: 80%;background-color: white;border-radius: 20px;padding: 20px;box-sizing: border-box;">
        <div style="color: #666; display: flex; align-items: center;">
          分享：<strong style="color: #333">{{ data.share.name }}</strong>
          <i class="iconfont-myicons" style="margin-left: 20px; margin-right: 5px">&#xe6f1;</i> {{
            data.share.shareTime
          }}
          <span style="margin-left: 20px">
          <i class="iconfont-myicons" style="margin-right: 5px">&#xe826;</i>
          <span v-if="data.share.status?.includes('小时')" style="color: red">{{ data.share.status }}</span>
          <span v-else>{{ data.share.status }}</span>
        </span>
        </div>


        <div>
          <div style="padding:10px;">
            <span style="cursor: pointer;font-size: 15px;color: #8c99a6" @click="loadAllData">全部文件 </span>
            <span style="cursor: pointer;font-size: 15px;color: #8c99a6" @click="loadFolderData(item.fileId)"
                  v-for="item in data.folders" :key="item.fileId">
          <span style="color: #72767b;font-size: 15px" class="iconfont-myicons">&#xe7b9;</span> {{
                item.fileName
              }}</span>
          </div>
          <el-table size="small" stripe :data="data.tableData">
            <el-table-column label="名称">
              <template v-slot="scope">
                <div style="display: flex; cursor: pointer;" @click="openFile(scope.row)">
                  <div style="flex: 1;display: flex;align-items: center">
                  <span v-html="getFileIcon(scope.row.fileType)"
                        style="color: #409EFF; font-size: 25px"
                        class="iconfont-myicons">
                  </span>
                    <span style="margin-left: 5px;font-size: 15px">{{ scope.row.fileName }}</span>
                  </div>
                  <div style="color: #409EFF; font-size: 14px">
                    <el-tooltip content="下载" effect="light" :open-delay="1000" v-if="scope.row.fileType !== 'folder'">
                      <i class="iconfont-myicons" style="margin-right: 10px; cursor: pointer"
                         @click="download(scope.row.filePath)">&#xe66c;</i>
                    </el-tooltip>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="lastModifiedTime" label="更新时间" width="200"></el-table-column>
            <el-table-column prop="size" label="文件大小（KB）" width="200"></el-table-column>
          </el-table>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {reactive} from "vue";
import request from "@/utils/request.js";
import {API_BASE_URL} from "@/config.js";

const route = useRoute();

const data = reactive({
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 10,
  //数据条数
  total: 0,
  code: route.query.code,
  shareId: route.query.shareId,
  share: {},
  validateFailed: false,   // 验证成功
  tableData: [],
  folderId: route.query.folderId,//点击打开的文件夹id
  fromUserId: route.query.from,//分享人id
  folders: [],
})

const Load = () => {
  if (data.folderId) {//文件夹ID存在，说明点击的是文件夹，访问接口查询该文件夹下的文件有哪些
    localStorage.setItem("comeInFileId", data.folderId)
    request.get(`/java/file/findFirstLayerFiles?current=${data.currentPage}&size=${data.pageSize}&UserId=${data.fromUserId}&OpenFolderId=${data.folderId}`).then((res) => {
      console.log(res)
      data.tableData = res.data.records;
      data.total = res.data.total;
      getParentFolderNames();
      if (localStorage.getItem("shareInfo") != null) {
        data.share = JSON.parse(localStorage.getItem("shareInfo"));
      }
    })
  } else {//文件夹ID存在，文件ID不存在，从访问路径拿到分享的ID，查询对应的文件
    request.get(`/java/share/getShareById?shareId=${data.shareId}`).then((res) => {
      data.share = res.data || {}
      data.tableData = res.data ? [res.data] : []
      console.log("res.data或者说shareInfo:", res.data)
      //验证code
      if (res.data.code !== data.code) {//验证失败
        data.validateFailed = true
      }
      localStorage.setItem("comeInFileId", res.data.fileId)
      localStorage.setItem("shareInfo", JSON.stringify(res.data));
      getParentFolderNames();
    })
  }
}

Load();

// 对应的文件类型和图标
const iconMap = reactive({
  folder: '&#xeb12;',
  doc: '&#xe63d;',
  jpg: '&#xe639;',
  png: '&#xe641;',
  pdf: '&#xe63a;',
  mp4: '&#xe63e;',
  docx: '&#xe643;',
  // pptx: '&#xe600;',
  // xlsx: '&#xe624;',
  md: '&#xe64c;',
  // jpeg: '&#xe619;',
  zip: '&#xe63c;',
});

// 计算属性，基于文件类型返回相应的图标
const getFileIcon = (fileType) => {
  return iconMap[fileType] || '&#xe644;'; // 如果没有找到匹配的图标，则返代表文件的图标
};

const openFile = (row) => {
  if (row.fileType !== 'folder') {
    const inlinePreviewTypes = [
      'jpg', 'jpeg', 'png', 'pdf', 'gif', 'bmp', 'svg', 'tiff', 'html', 'txt', 'svg',
      'json', 'js', 'css', 'xml', 'xlsx', 'zip', 'rar', 'mp3', 'mp4', 'java', 'cpp', 'c', 'c#',
      'php', 'go', 'python', 'swift', 'kotlin', 'rust', 'scala', 'ruby', 'perl', 'lua',
      'javascript', 'typescript', 'less', 'scss','doc','docx'
    ];
    // 将文件类型转换为小写以进行不区分大小写的比较
    const fileType = row.fileType.toLowerCase();
    if (inlinePreviewTypes.includes(fileType)) {
      // 网页另外开一个标签页打开  http://localhost:8080/disk/preview/64
      const url = `${API_BASE_URL}/disk/preview/${row.fileId}`;
      // 使用JavaScript的window.open方法在新标签页中打开链接
      window.open(url, '_blank');
    }
  } else {//是文件夹
    location.href = '/downShare?code=' + data.code + '&shareId=' + data.shareId + '&folderId=' + row.fileId + '&from=' + data.fromUserId
  }
}

//文件下载
const download = (filePath) => {
  window.open(filePath);
}


//全部文件
const loadAllData = () => {
  let comeInFileId = localStorage.getItem("comeInFileId");
  location.href = '/downShare?code=' + data.code + '&shareId=' + data.shareId + '&from=' + data.fromUserId + '&folderId=' + comeInFileId
  localStorage.removeItem("comeInFileId");
}


// 加载文件夹 面包屑用
const loadFolderData = (fileId) => {
  data.folderId = fileId;
  Load();
}

const getParentFolderNames = () => {
  if (data.folderId) { //展开文件夹后才发请求获取上级的目录
    request.get(`/java/file/findParentFolder?FolderId=${data.folderId}`)
        .then((response) => {
          console.log("getParentFolderNames:", response);
          data.folders = response.data;
        })
        .catch((error) => {
          console.error('请求发生错误:', error);
        })
        .finally(() => {

        });
  }
}

</script>

<style scoped>
.card {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
</style>